import { useHistory } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';

const Header = () => {
  const history = useHistory();
  const { user, logout } = useAuth();
  
  const handleLogout = async () => {
    await logout();
    history.push('/login');
  };
  
  // 获取用户显示名称
  const getUserDisplayName = () => {
    if (user?.firstName && user?.lastName) {
      return `${user.firstName} ${user.lastName}`;
    }
    if (user?.firstName) {
      return user.firstName;
    }
    if (user?.email) {
      return user.email.split('@')[0];
    }
    return 'User';
  };

  // 获取用户头像字母
  const getUserAvatarLetter = () => {
    const displayName = getUserDisplayName();
    return displayName.charAt(0).toUpperCase();
  };
  
  return (
    <header className="bg-gray-800 text-white p-4">
      <div className="container mx-auto flex justify-between items-center">
        <h1 className="text-xl font-bold">RoomAI</h1>
        <nav>
          <ul className="flex space-x-4 items-center">
            <li><a href="/design" className="hover:text-gray-300">设计</a></li>
            {/* 其他导航项 */}
            {user ? (
              <>
                <li>
                  {user?.picture ? (
                    <img
                      src={user.picture}
                      alt="User Avatar"
                      className="w-8 h-8 rounded-full object-cover"
                    />
                  ) : (
                    <div className="w-8 h-8 rounded-full bg-blue-500 flex items-center justify-center text-white">
                      {getUserAvatarLetter()}
                    </div>
                  )}
                </li>
                <li>
                  <button 
                    onClick={handleLogout}
                    className="bg-red-600 hover:bg-red-700 px-3 py-1 rounded"
                  >
                    登出
                  </button>
                </li>
              </>
            ) : (
              <li>
                <a href="/login" className="hover:text-gray-300">登录</a>
              </li>
            )}
          </ul>
        </nav>
      </div>
    </header>
  );
};

export default Header;